package com.ethan.controller;

import com.ethan.pojo.Result;
import com.ethan.pojo.User;
import com.ethan.service.UserService;
import com.ethan.utils.JwtUtil;
import com.ethan.utils.Md5Util;
import com.ethan.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        //1.查询用户是否存在
        User user = userService.findUserByUsername(username);
        System.out.println(user);
        if (user != null) {
            return Result.error("用户已存在！");
        }
        //2.注册用户
        try {
            userService.addUser(username, password);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }

        return Result.success();
    }

    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        //1.根据用户名查询User
        User user = userService.findUserByUsername(username);
        System.out.println(user);
        String ppp = Md5Util.getMD5String(password);
        if(user == null){
            return Result.error("用户名错误！");
        }
        //2.判断用户是否存在并验证密码
        if(ppp.equals(user.getPassword())) {
            HashMap<String, Object> claims = new HashMap<>();
            claims.put("id", user.getId());
            claims.put("username", user.getUsername());
            String token = JwtUtil.genToken(claims);
            //把token存储到redis中
            stringRedisTemplate.opsForValue().set(token, token,12, TimeUnit.HOURS);
            return Result.success(token);
        }
        return Result.error("密码错误！");
    }

    @GetMapping("/userInfo")
    public Result<User> userInfo() {
        Map<String, Object> claims = ThreadLocalUtil.get();
        String username = (String) claims.get("username");
        User user = userService.findUserByUsername(username);
        return Result.success(user);
    }

    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user) {
        user.setUpdateTime(LocalDateTime.now());
        userService.update(user);
        return Result.success();
    }

    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl) {

        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> params, @RequestHeader("Authorization") String token) {
        //1.获取参数并校验是否存在
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");

        if(!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)) {
            return Result.error("必填参数缺失！");
        }
        //2.判断原密码是否正确
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User loginUser = userService.findUserByUsername(username);
        if(!loginUser.getPassword().equals(Md5Util.getMD5String(oldPwd))) {
            return Result.error("原密码验证错误！");
        }
        //3.判断两次新密码是否一致
        if(!newPwd.equals(rePwd)) {
            return Result.error("两次新密码输入不一致！");
        }
        //4.旧密码不能和新密码一致
        if (newPwd.equals(oldPwd)){
            return Result.error("新旧密码不能一致！");
        }
        //5.调用service更新密码
        userService.updatePwd(newPwd);
        //删除redis中的token
        stringRedisTemplate.opsForValue().getOperations().delete(token);
        return Result.success();
    }
}
